import numpy as np
#创建向量
vector=np.array([1,2,3,4,5,6])
#创建矩阵
matrix=np.array([[1,2,3],
                [4,5,6],
                [7,8,9]])
print(vector)
print(matrix)

#向量和矩阵的基本属性
# 向量的维度
print(vector.shape) # (6, )
# 矩阵的维度
print(matrix.shape) # (3, 3)
# 矩阵的行数和列数
print(matrix.shape[0])  # 行数, 3
print(matrix.shape[1])  # 列数, 3

#索引和切片
# 索引
print(vector[0])  # 输出第一个元素, 1
print(matrix[1, 1])  # 输出第二行第二列的元素, 5

# 切片

print(vector[0:2])  # 输出前两个元素, [1, 2]
print(matrix[0:2, 0:2])  # 输出左上角的2x2子矩阵, [[1, 2], [4, 5]]


#向量矩阵的运算
# 向量加法
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])
print("向量加法")
print(np.add(vector1, vector2))
# [5, 7, 9]

# 矩阵乘法
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print("矩阵乘法结果：")
print(np.dot(matrix1, matrix2))  
# 或使用 matrix1 @ matrix2
print(matrix1@matrix2)
# [[19, 22],
#  [43, 50]]

#利用Numpy进行线性代数基本运算
# 数量乘法示例
scalar = 5
scaled_vector = scalar * vector
print("数量乘法：")
print("Scaled vector:", scaled_vector)
# Scaled vector: [ 5 10 15]

# 矩阵的转置示例
transposed_matrix = matrix.T
print("矩阵转置：")
print("Transposed matrix:\n", transposed_matrix)
# Transposed matrix:
# [[1, 4, 7]
#  [2, 5, 8]
#  [3, 6, 9]]

# 计算行列式示例
matrix_determinant = np.linalg.det(matrix)
print("计算行列式：")
print("Matrix determinant:", matrix_determinant)
# Matrix determinant: 0.0

# 求解线性方程组示例
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
solution = np.linalg.solve(A, b)
print("线性方程组：")
print("Solution of the linear system:", solution)
# Solution of the linear system: [2. 3.]

#numpy.linalg 的使用
#import numpy as np
#计算逆矩阵
# If the matrix is singular, use the pseudo-inverse
pseudo_inverse_matrix = np.linalg.pinv(matrix)
print("Pseudo-inverse of the matrix:")
print(pseudo_inverse_matrix)
# Pseudo-inverse of the matrix:
# [[-6.38888889e-01 -1.66666667e-01  3.05555556e-01]
#  [-5.55555556e-02  4.20756436e-17  5.55555556e-02]
#  [ 5.27777778e-01  1.66666667e-01 -1.94444444e-01]]

#特征值和特征向量
eigenvalues, eigenvectors = np.linalg.eig(matrix)
print("特征值：")
print(eigenvalues)
# [ 1.61168440e+01 -1.11684397e+00 -1.30367773e-15]
print("特征向量：")
print(eigenvectors)
# [[-0.23197069 -0.78583024  0.40824829]
#  [-0.52532209 -0.08675134 -0.81649658]
#  [-0.8186735   0.61232756  0.40824829]]


#奇异值分解
U, S, V = np.linalg.svd(matrix)
print(U)
# [[-0.21483724  0.88723069  0.40824829]
#  [-0.52058739  0.24964395 -0.81649658]
#  [-0.82633754 -0.38794278  0.40824829]]
print(S)
# [1.68481034e+01 1.06836951e+00 4.41842475e-16]
print(V)
# [[-0.47967118 -0.57236779 -0.66506441]
#  [-0.77669099 -0.07568647  0.62531805]
#  [-0.40824829  0.81649658 -0.40824829]]

#范数计算
norm = np.linalg.norm(vector)
print("范数计算：")
print(norm)
# 3.7416573867739413